package com.qihoo.finance.fake.variety;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class VarietyServiceFactory {
    Logger logger = LogManager.getLogger(VarietyServiceFactory.class);
    @Autowired
    private List<VarietyService> varietyServiceList;

    private static Map<String, VarietyService> varietyServiceMap = new ConcurrentHashMap<>();

    public VarietyServiceFactory(List<VarietyService> varietyServiceList) {
        this.varietyServiceList = varietyServiceList;
    }

    @PostConstruct
    public void init() {
        if (CollectionUtils.isEmpty(varietyServiceList)) {
            logger.warn("VarietyService注入为空！");
        } else {
            logger.info("VarietyService实现类加载开始，待加载列表实例数量：{}", varietyServiceList.size());
            varietyServiceList.forEach(
                    b -> {
                        logger.info("[VarietyService]实现类加载，当前加载类型：{}", b.getVarietyType());
                        Object exists = varietyServiceMap.putIfAbsent(b.getVarietyType().getVariety(), b);
                        if (exists != null) {
                            throw new IllegalArgumentException("[VarietyService]类型冲突，请检查配置: " + b.getVarietyType() +
                                    ",已存在: " + ClassUtils.getShortName(exists.getClass()) +
                                    ",待新增: " + ClassUtils.getShortName(b.getClass()));
                        }
                    }
            );
            logger.info("VarietyService实现类加载完毕，共加载[{}]种类型", varietyServiceMap.size());
        }
    }

    public static VarietyService getVarietyServiceByType(String varietyType) {
        return varietyServiceMap.get(varietyType);
    }
}
